#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <iostream>

using namespace std;

// the format string for the sprintf() call below. %d is filled with a
// string representation of an integer. the size that this string
// representation will take as many bytes as necessary.
#define PIDMSG "Dieses Programm hat PID %d"

int main()
{
    pid_t pid = getpid();

    // allocate bytes on the heap, to contain the formatted
    // message.

    // the bug is that

    // 1. sizeof(pid) is not enough to hold any string representation
    //    of a pid_t. a pid_t is 4 bytes, and PID 12345 is 5 bytes for
    //    example.

    // 2. even if the PID in question is 1234 (4 bytes), there is no
    //    room for the terminating 0-byte that is added by sprintf().
    
    char* msg = new char[strlen(PIDMSG) + sizeof(pid)];
    sprintf(msg, PIDMSG, pid);
    cout << msg << endl;

    // don't forget to clean up
    delete[] msg;

    return 0;
}
